package com.coocaa.ops.admin.v1.timedtask.service.impl;


import com.coocaa.ops.admin.v1.audit.service.AuditTaskProviderManager;
import com.coocaa.ops.admin.v1.timedtask.TimedTaskUtil;
import com.coocaa.ops.admin.v1.timedtask.convert.TimedTaskSaveConverter;
import com.coocaa.ops.admin.v1.timedtask.enums.TaskStatusEnums;
import com.coocaa.ops.admin.v1.timedtask.job.impl.MyQuartzJobServiceImpl;
import com.coocaa.ops.admin.v1.timedtask.model.TimedInfoModel;
import com.coocaa.ops.admin.v1.timedtask.provider.impl.TimedTaskProviderImpl;
import com.coocaa.ops.admin.v1.timedtask.service.ITimedTaskService;
import com.coocaa.ops.admin.v1.timedtask.validator.TimedTaskValidator;
import com.coocaa.ops.common.core.base.enums.ResourceStatusEnums;
import com.coocaa.ops.common.core.base.model.R;
import com.coocaa.ops.common.core.base.model.ResourceBaseModel;
import com.coocaa.ops.common.core.biz.timedtask.entity.TimedTaskInfoEntity;
import com.coocaa.ops.common.tool.base.InstanceUtil;
import com.coocaa.ops.common.tool.date.DateUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.PostConstruct;
import java.util.Map;

/**
 * @author bijiahao
 * @date : 2018/5/22.
 * @description
 */
@Service
public class TimedTaskServiceImpl implements ITimedTaskService {
    @Autowired
    private TimedTaskProviderImpl timedTaskProvider;
    @Autowired
    private AuditTaskProviderManager auditTaskProviderManager;
//    @Autowired
//    private MediaNotifyBizImpl mediaNotifyBiz;
//    @Autowired
//    @Lazy
//    private MyAsyncOpsMgrServiceImpl myAsyncOpsMgrService;
    @Autowired
    private MyQuartzJobServiceImpl myQuartzJobService;

    /**
     * 初始化配置
     */
    @PostConstruct
    private void init() {
        TimedTaskUtil.setTimedTaskService(this);
    }

    public TimedTaskProviderImpl getTimedTaskProvider() {
        return timedTaskProvider;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public Map cancelTimedTask(ResourceBaseModel resourceBaseModel, Integer userId) {
        //资源ID
        Integer id = resourceBaseModel.getId();
        //资源版本
        Integer version = resourceBaseModel.getVersion();
        //资源类别
        String type = resourceBaseModel.getType();
        TimedTaskInfoEntity currentTimedTask = timedTaskProvider.queryTimedTaskForTimelyShelves(type, id, version);
        if (TimedTaskValidator.isNoExistTask(currentTimedTask)) {
            //定时任务不存在
            R.fail(TaskStatusEnums.NO_TASK.getDesc());
        }
        //定时要到期的时间
        long timedTaskTime = currentTimedTask.getReleaseTime().getTime();
        long currentTime = System.currentTimeMillis();
        //间隔时间
        long intervalTime = timedTaskTime - currentTime;
        if (TimedTaskValidator.isCanNotCancelTask(intervalTime)) {
            //如果小于2分钟-定时任务不能取消
            return  R.fail(TaskStatusEnums.TASK_CAN_NOT_CANCEL.getDesc());
        }
        if (!timedTaskProvider.getTimedTaskBiz().isCanCancelTimedTask(resourceBaseModel.getId(), resourceBaseModel.getType())){
            return  R.fail(TaskStatusEnums.TASK_HAS_NOT_ONLINE_COPY.getDesc());
        }
        //重新执行情况
        if (TimedTaskValidator.isTaskToExecuteRightNow(intervalTime, currentTimedTask)) {
            //重新执行定时任务
            this.handleTaskRefresh(id, version, type, userId);
            return R.fail(TaskStatusEnums.TASK_HAS_EXECUTED_RIGHT_NOW.getDesc());
        }
        //执行完毕情况
        if (TimedTaskValidator.isTaskHasFinished(intervalTime, currentTimedTask)) {
            return  R.fail(TaskStatusEnums.TASK_HAS_FINISHED.getDesc());
        }
        //正常取消
        myQuartzJobService.delJob(currentTimedTask);
        timedTaskProvider.deleteById(currentTimedTask.getId());
        auditTaskProviderManager.cancelTask(id, version, userId, type);

        return  R.ok().msg(TaskStatusEnums.TASK_NORMAL_CANCEL.getDesc());
    }

    /**
     * 定时数量限制
     *
     * @return
     */
    @Override
    public Object taskLimit() {
//        if (timedTaskProvider.queryLimitTaskNum() > SystemProperties.SystemConstants.TIME_TASK_LIMIT) {
//            return R.fail("定时任务不能提交啦");
//        }
        return R.ok().msg("定时任务可继续提交");
    }

    /**
     * 获取定时信息-根据ID-版本-类型
     *
     * @param id
     * @param version
     * @param type
     * @return
     */
    @Override
    public Object getTimedInfo(Integer id, Integer version, String type) {
        TimedTaskInfoEntity entity = timedTaskProvider.queryTimedTaskForTimelyShelves(type, id, version);
        Map<String, Object> data = InstanceUtil.newHashMap(1);
        data.put("releaseTime", entity == null ? "" : entity.getReleaseTime());
        return data;
    }

    /**
     * 处理版面，板块等定时上架
     *
     * @param timedInfoModel
     * @param resourceType
     */
    @Override
    public void handleTimedTask(TimedInfoModel timedInfoModel, String resourceType) {
        Integer isTiming = timedInfoModel.getIsTiming();
        if (null != isTiming && isTiming == 1) {
            TimedTaskInfoEntity timedTaskInfo = timedTaskProvider.queryTimedTaskForTimelyShelves(resourceType, timedInfoModel.getResourceId(), timedInfoModel.getCurrentVersion());
            // 新增定时任务
            if (timedTaskInfo == null) {
                TimedTaskInfoEntity timedTaskInfoEntity = TimedTaskSaveConverter.getTimedTaskInfoEntityForTimelyShelves(timedInfoModel.getResourceId(), resourceType, timedInfoModel.getCurrentVersion(), ResourceStatusEnums.TO_AUDITING.getStatus(), timedInfoModel.getUserId(), DateUtil.getCurDate(), timedInfoModel.getReleaseTime());
                timedTaskProvider.save(timedTaskInfoEntity);
            } else {
                // 修改定时任务
                TimedTaskInfoEntity timedTaskInfoEntity = new TimedTaskInfoEntity(ResourceStatusEnums.TO_AUDITING.getStatus(), timedInfoModel.getUserId(), timedInfoModel.getReleaseTime());
                timedTaskInfoEntity.setId(timedTaskInfo.getId());
                timedTaskProvider.updateById(timedTaskInfoEntity);
            }
        } else {
            //之前定时，后来取消的情况
            TimedTaskInfoEntity timedTaskInfo = timedTaskProvider.queryTimedTaskForTimelyShelves(resourceType, timedInfoModel.getResourceId(), timedInfoModel.getCurrentVersion());
            if (null != timedTaskInfo && timedTaskInfo.getStatus() == ResourceStatusEnums.TO_AUDITING.getStatus()) {
                timedTaskProvider.deleteById(timedTaskInfo.getId());
            }
        }
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean execPutShelvesAndUpdateStatus(TimedTaskInfoEntity entity) {
        //上架操作
        auditTaskProviderManager.putShelves(entity.getResourceId(), entity.getResourceVersion(), entity.getCurrentOperator(), entity.getResourceType());
        //将定时任务状态 设置【状态4-审核通过已上线】
        timedTaskProvider.updateTimedTaskStatusById(entity.getId(), ResourceStatusEnums.ON_LINE.getStatus());
        return true;
    }


    /*************** ===私有方法=== ********************* ===start=== ***************************************/

    /**
     * 处理定时任务重新执行
     *
     * @param id
     * @param version
     * @param type
     * @param userId
     */
    private void handleTaskRefresh(Integer id, Integer version, String type, Integer userId) {
        //定时任务重新执行
        //上架
        auditTaskProviderManager.putShelves(id, version, userId, type);
        //将定时任务状态 设置【状态4-审核通过已上线】
        TimedTaskInfoEntity currentTimedTask = timedTaskProvider.queryTimedTaskForTimelyShelves(type, id, version);
        timedTaskProvider.updateTimedTaskStatusById(currentTimedTask.getId(), ResourceStatusEnums.ON_LINE.getStatus());
        //需要执行的异步操作 统一处理
//        myAsyncOpsMgrService.handleCommonAsyncOps(ResourceBaseModel.getResourceBaseModel(type, id, version), userId);
    }

}
